package server;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    Map<String ,Object> c;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }
    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap,Map<String ,Object> c) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.c = c;
    }


    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                String[] url= request.getUrl().trim().split("/");

                Object object=c.get("/"+url[1]);
                if(object==null){
                    response.output("====未找到相关处理器=======");
                    System.out.println("====未找到相关处理器=======");
                    return;
                }

                Class<?> aClass =(Class<?>)object;
                Object obj = aClass.newInstance();
                Method method = aClass.getMethod(url[2]);
                method.invoke(obj);

                response.output("==="+request.getUrl());

            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }



            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
